/* * @Author: Joker * @Date: 2017-11-28 12:18:04 * @Last Modified by: Joker * @Last Modified time: 2017-11-28 13:51:53 */
<template>
  <div style="height: 100%">
    <header>
      <el-row :gutter="20">
        <el-col :span="8">
          <div>
            <div CLASS="logo">
              <img src="../../assets/logo.png" />
              <b>数字化施工管理平台</b>
              <font size="-2">V.1.0</font>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="bread_title">
            {{breadTitle}}
          </div>
        </el-col>
        <el-col :span="8">
          <div class="operate">
            <el-input placeholder="在当前模块下搜索" v-model="input23" size="mini" class="search_input">
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
            <el-tooltip class="item" effect="dark" content="消息" placement="bottom-end" v-if="messageRole.have">
              <i :class="['fa','fa-bell',activeIndex === 'message' ? 'icon_active' : '']" @click="linkTo('message')"></i>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="系统管理" placement="bottom-end" v-if="systemRole.have">
              <i :class="['fa','fa-sitemap',activeIndex === 'management' ? 'icon_active' : '']" @click="linkTo('management')"></i>
            </el-tooltip>
            <el-dropdown :hide-on-click="false" @command="loginOut">
              <i class="fa fa-user-circle-o"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="update">
                  修改密码
                </el-dropdown-item>
                <el-dropdown-item command="loginOut" divided>退出</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </el-col>
      </el-row>
    </header>
    <transition name="fade">
      <div v-if="isMenu" class="zindex-menu">
        <el-menu :default-active="activeIndex+''" class="el-menu-demo" mode="horizontal" @select="handleSelect" background-color="#434a57"
          style="line-height: 50px;height: 51px;padding-left:30px;" text-color="#fff" active-text-color="#ffa24a">
          <template v-for="menu in menuList">
              <el-menu-item :index="menu.id+''" v-if="!menu.children">
                <router-link :to="menu.menuUrl" :key="menu.id">
                  <i :class="menu.ficon"></i>{{menu.label}}
                </router-link>
              </el-menu-item>
              <el-submenu :index="menu.id+''" v-else="menu.children && menu.children.length>0">
                <template slot="title"><i :class="menu.ficon"></i>{{menu.label}}</template>
                <router-link :to="item.menuUrl" v-for="item in menu.children" :key="item.id">
                  <el-menu-item :index="item.id+''">{{item.label}}</el-menu-item>
                </router-link>
              </el-submenu>
              </span>
          </template>
        </el-menu>
      </div>
    </transition>
    <router-view class="subPage" />
    <el-dialog title="修改密码" :close-on-click-modal="false" :visible.sync="dialogVisible" width="600px" @close="handleClose('ruleForm')">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="旧密码" prop="oldPass">
          <el-input type="password" v-model.trim="ruleForm.oldPass" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPass">
          <el-input type="password" v-model.trim="ruleForm.newPass" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model.trim="ruleForm.checkPass" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="updatePass">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    projectManagement,
    login
  } from "../../service/service_zbw";
  import {
    deepClone,
    formCheck
  } from "../../lib/utils";
  import {
    mapState,
    mapMutations,
    mapActions
  } from 'vuex';

  export default {
    computed: {
      ...mapState({
        client: state => state.client,
        userRole: state => state.userRole,
        menuList: state => state.menuList,
      }),
    },
    data() {
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm.newPass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        //系统管理权限
        systemRole: {},
        //消息管理权限
        messageRole: {},
        //资产管理权限
        assetRole: {},
        input23: '',
        activeIndex: 76,
        breadTitle: '',
        isMenu: true,
        isIcon: true,
        dialogVisible: false,
        ruleForm: {
          oldPass: '',
          newPass: '',
          checkPass: '',
        },
        rules: {
          oldPass: [{
              required: true,
              message: '请输入旧密码',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 15,
              message: '密码长度不大于15个字符',
              trigger: 'blur'
            }
          ],
          newPass: [{
              required: true,
              message: '请输入新密码',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 15,
              message: '密码长度不大于15个字符',
              trigger: 'blur'
            }
          ],
          checkPass: [{
            required: true,
            validator: validatePass2,
            trigger: 'blur'
          }],
        }
      };
    },
    methods: {
      ...mapMutations([
        'SET_CLIENT',
        'SET_PROJECTID',
        'SET_MENULIST'
      ]),
      ...mapActions([
        'clearAll'
      ]),
      /**
       * 页面初始化调用
       */
      async init() {
        let res = await projectManagement.getProList();
        let pro = [];
        if (res.success) {
          if (res.success) {
            pro = res.obj;
          }
        }
        let arr = [];
        for (let i of this.userRole.menuPermissionList) {
          if (i.id === 45) {
            //系统管理
            this.systemRole = deepClone(i);
          } else if (i.id === 47) {
            //消息管理
            this.messageRole = deepClone(i);
          } else {
            if (i.id === 46) {
              this.assetRole = deepClone(i);
              let obj = deepClone(i);
              for (let i of obj.children) {
                if (i.have) {
                  obj.menuUrl = i.menuUrl;
                  break;
                }
              }
              delete obj.children;
              if (i.have) {
                arr.push(obj);
              }
              continue;
            } else if (i.id === 48) {
              let obj = deepClone(i);
              obj.children = [];
              for (let j of pro) {
                obj.children.push({
                  id: j.projectId + 'project',
                  label: j.name,
                  menuUrl: `${obj.menuUrl}/${j.projectId}`
                });
              }
              obj.menuUrl = '';
              if (i.have) {
                arr.push(obj);
              }
              continue;
            }
            //主菜单
            if (i.have) {
              arr.push(i);
            }
          }
        }
        this.SET_MENULIST(arr);
        this.$nextTick(() => {
          //判断当前是否有操作痕迹
          if (sessionStorage.getItem('MENUACTIVEINDEXARRAY') || sessionStorage.getItem('MENUACTIVESTRING')) {
            //判断当前是整成菜单栏  还是右上角的图标菜单
            if (sessionStorage.getItem('MENUACTIVESTRING')) {
              //图标菜单
              let indexArray = sessionStorage.getItem('MENUACTIVESTRING').split(',');
              this.activeIndex = indexArray[0];
              this.breadTitle = indexArray[1];
              this.linkTo(indexArray[2]);
            } else {
              //正常菜单
              let indexArray = sessionStorage.getItem('MENUACTIVEINDEXARRAY').split(',');
              this.activeIndex = indexArray[indexArray.length - 1];
              this.findNameById(indexArray);
            }
          } else {
            if (typeof this.menuList !== 'undefined' && typeof this.menuList[0] !== 'undefined') {
              //无操作痕迹  默认选中第一个菜单
              if (typeof this.menuList[0].children !== 'undefined' && this.menuList[0].children) {
                //第一个菜单有子菜单
                this.activeIndex = this.menuList[0].children[0].id;
                this.breadTitle = this.menuList[0].children[0].label;
                this.$router.push(this.menuList[0].children[0].menuUrl);
              } else {
                //第一个菜单无子菜单
                this.activeIndex = this.menuList[0].id;
                this.breadTitle = this.menuList[0].label;
                this.$router.push(this.menuList[0].menuUrl);
              }
            } else if (this.messageRole && this.messageRole.have) {
              this.linkTo('message');
            } else if (this.systemRole && this.systemRole.have) {
              this.linkTo('management');
            }

          }
        })
      },
      /**
       * 退出
       */
      async loginOut(val) {
        if (val === 'update') {
          this.dialogVisible = true;
          return;
        }
        let res = await login.logout();
        if (res.success) {
          //移除菜单选中
          sessionStorage.removeItem('MENUACTIVEINDEXARRAY');
          //移除icon菜单选中
          sessionStorage.removeItem('MENUACTIVESTRING');
          //移除设备管理二级菜单选中
          sessionStorage.removeItem('ASSETINDEX');
          //移除系统管理二级菜单选中
          sessionStorage.removeItem('SYSTEMACTIVEINDEX');
          sessionStorage.removeItem('USERTOKEN');
          this.clearAll();
          this.$router.push('/login');
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      },
      async updatePass() {
        let flag = formCheck(this, 'ruleForm');
        if (!flag) {
          return;
        }
        let param = {
          newPassword: this.ruleForm.newPass,
          oldPassword: this.ruleForm.oldPass
        };
        if (param.newPassword === param.oldPassword) {
          this.$message({
            type: 'warning',
            message: '新旧密码不能相同,请重新输入'
          });
          return;
        }
        let res = await login.updatePass(param);
        if (res.success) {
          this.loginOut('loginOut');
          this.handleClose('ruleForm');
          this.$message({
            type: 'success',
            message: res.msg
          });
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      },
      handleClose(formName) {
        this.dialogVisible = false;
        this.$refs[formName].resetFields();
      },
      /**
       * 菜单栏选中更改
       */
      handleSelect(key, keyPath) {
        this.SET_PROJECTID(key);
        //记录菜单选中
        sessionStorage.setItem('MENUACTIVEINDEXARRAY', keyPath);
        //移除icon菜单选中
        sessionStorage.removeItem('MENUACTIVESTRING');
        //移除设备管理二级菜单选中
        sessionStorage.removeItem('ASSETINDEX');
        //移除系统管理二级菜单选中
        sessionStorage.removeItem('SYSTEMACTIVEINDEX');
        this.activeIndex = key;
        this.findNameById(keyPath);
      },
      /**
       * 查找选中菜单的名称
       */
      findNameById(param) {
        if (param instanceof Array) {
          if (param.length > 1) {
            let first = this.findItem(this.menuList, param[0]);
            let second = this.findItem(first.children, param[1]);
            this.breadTitle = second.label;
          } else {
            let item = this.findItem(this.menuList, param[0]);
            this.breadTitle = item.label;
          }
        }
      },
      /**
       * 查找具体的选中名
       */
      findItem(datas, index) {
        for (let i of datas) {
          if ((i.id + '') === index) {
            return i;
          }
        }
      },
      /**
       * 跳转至系统设置页面
       */
      linkTo(param) {
        if (param === this.activeIndex) {
          return;
        }
        //选中消息管理或系统管理，取消菜单栏的选中样式
        this.isMenu = false;
        this.activeIndex = param;
        this.isMenu = true;
        //根据选中做出对应跳转
        if (param === 'management') {
          this.breadTitle = '系统管理';
          this.$router.push('/index/systemManagement');
        } else {
          this.breadTitle = '消息管理';
          this.$router.push('/index/messageManagement');
        }
        sessionStorage.setItem('MENUACTIVESTRING', [this.activeIndex, this.breadTitle, param]);
      },
      /**
       * 监听window的宽高
       */
      watchWindow(width, height) {
        this.SET_CLIENT({
          width: width,
          height: height
        });
      }
    },
    mounted() {
      this.init();
      this.watchWindow(document.documentElement.clientWidth, document.documentElement.clientHeight);
      // 然后监听window的resize事件．在浏览器窗口变化时再设置下背景图高度．
      window.onresize = () => {
        return (() => {
          this.watchWindow(document.documentElement.clientWidth, document.documentElement.clientHeight);
        })()
      };
    }
  }

</script>

<style scoped>
  header {
    width: inherit;
    background: #fff;
    height: 50px;
    line-height: 50px;
  }

  .bread_title {
    text-align: center;
    font-size: 20px;
  }

  .operate {
    text-align: right;
    margin-right: 30px;
  }

  .operate .search_input {
    width: 70%;
    max-width: 200px;
  }

  .operate .icon {
    height: 28px;
    font-size: 22px;
    margin-top: 4px;
    margin-left: 15px;
    cursor: pointer;
  }

  .logo {
    font-size: 16px;
    overflow: hidden;
    height: 50px;
    margin-left: 15px;
  }

  .logo font {
    font-style: oblique;
  }

  .logo img {
    vertical-align: middle;
    display: inline-block;
    margin: 0 15px;
    margin-top: -1px;
  }
  /* 选中样式 */

  .icon_defaulte {
    color: #000;
  }

  .icon_active {
    color: rgb(255, 162, 74);
  }
  /* 消除菜单选中效果去除时的过渡效果 */

  .fade-enter-active,
  .fade-leave-active {
    transition: opacity .1s
  }

  .fade-enter,
  .fade-leave-to {
    opacity: 1
  }
  /* 子页面的宽度限制 */

  .subPage {
    width: 100%;
    padding: 0 30px;
    margin-top: 20px;
  }

</style>

